from copy import deepcopy
from app.customer.model import Customer as CustomerTable
from app.customer import dao
from common.mixins import DictMixin
from common.utils.utils import custom_marshal_pagination
from common.utils.pinyin import get_first_letter_pinyin
from exts import db
from app.company.model import Company
from common import constant
from common import errors
import re

def add_default_coins():
    pass


def init_company_info():
    create_default_category()
    create_default_customer()


def create_default_category():
    default_data = {
        "name": "默认类别",
        "notes": "系统默认创建"
    }
    from app.product.category.model import Category
    Category.create(**default_data)


def create_default_customer():
    from app.customer.model import Customer
    Customer.create(**{
        "name": "默认供应商",
        "notes": "系统默认创建",
        "customer_type": constant.CustomerType.SUPPLIER.value
    })
    Customer.create(**{
        "name": "默认客户",
        "notes": "系统默认创建",
        "customer_type": constant.CustomerType.CLIENT.value

    })


# def create_default_warehouse():
#     from app.storage.warehouse.service import create
#     basic_data = [
#         {
#             "name": "货损仓",
#             "notes": "系统默认创建, 用于存放损坏商品"
#         },
#         {
#             "name": "退货仓",
#             "notes": "系统默认创建, 用于临时存放退货商品"
#         },
#     ]
#     create(**basic_data[0])
#     create(**basic_data[1])

def update_auto_sku_sn(sku_sn, company_id):
    company = Company.query.filter_by(id=company_id).first()

    # 匹配规则：前缀相同 数字位数相同
    re_str = 'PREFIX(\d{LEN_OF_NUMBER})$' \
        .replace('PREFIX', company.auto_sku_sn_prefix) \
        .replace('LEN_OF_NUMBER', str(company.auto_sku_sn_len))

    match = re.match(re_str, sku_sn)
    # 规则匹配成功
    if match:
        sku_sn_start_index = int(match.group(1))
        # 数组部分 大于等于
        if sku_sn_start_index >= company.auto_sku_sn_start_index:
            company.auto_sku_sn_start_index = sku_sn_start_index + 1
            # 更新自动生成货号
            # result = company.update()
            # if result:
            #     raise errors.DbCommitFailureException(result)
            return 'update new auto_sku_sn: ' + sku_sn
    return 'no match, not update ' + sku_sn
